﻿using System;
using System.IO;
using System.Reflection;

namespace Com.Lancetinc.Evs.Helpers;

public static class DirUtil
{
    private static Assembly GetAssembly()
    {
        var assembly = Assembly.GetEntryAssembly();
        if (assembly != null)
            return assembly;
        return Assembly.GetExecutingAssembly();
    }

    private static string _exeDirectory;
    /// <summary>
    /// 执行EXE所在文件夹
    /// </summary>
    public static string ExeDirectory
    {
        get
        {
            if (_exeDirectory != null)
                return _exeDirectory;
            _exeDirectory = Path.GetDirectoryName(GetAssembly().Location);
            return _exeDirectory;
        }
    }

    /// <summary>
    /// 确保目录已经存在，如果不存在则创建
    /// </summary>
    /// <param name="dir"></param>
    /// <returns>true:已经存在</returns>
    public static bool EnsureDirectoryExists(string dir)
    {
        if (Directory.Exists(dir))
        {
            return true;
        }

        Directory.CreateDirectory(dir);
        return false;
    }

    /// <summary>
    /// 复制文件夹
    /// </summary>
    /// <param name="sourceDir"></param>
    /// <param name="targetDir"></param>
    /// <param name="overwrite"></param>
    public static void CopyDirectory(string sourceDir, string targetDir, bool overwrite = true)
    {
        EnsureDirectoryExists(targetDir);

        var diSource = new DirectoryInfo(sourceDir);

        foreach (var fi in diSource.GetFiles())
        {
            var targetFile = Path.Combine(targetDir, fi.Name);
            try
            {
                File.Copy(fi.FullName, targetFile, overwrite);
            }
            catch
            {
                // ignore
            }
        }

        foreach (var subDir in diSource.GetDirectories())
        {
            var targetSubDir = Path.Combine(targetDir, subDir.Name);
            CopyDirectory(subDir.FullName, targetSubDir, overwrite);
        }
    }

    /// <summary>
    /// 删除目录及子目录
    /// </summary>
    /// <param name="dir"></param>
    public static void DeleteDirectory(string dir)
    {
        try
        {
            if (!Directory.Exists(dir))
                return;

            Directory.Delete(dir, true);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}